//
//  LivePlayerViewController.m
//  PolyvIJKLivePlayer
//
//  Created by ftao on 2016/12/14.
//  Copyright © 2016年 easefun. All rights reserved.
//

#import "LivePlayerViewController.h"
#import "PLVLivePlayerController.h"
#import "ZJZDanMu.h"
#import "PLVUtils.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

/// 播放器背景图片路径
#define PLAYER_BACKGROUND @"PLVLivePlayerSkin.bundle/plv_background"

@interface LivePlayerViewController ()

@property (nonatomic, strong) UIView *displayView;                          // 播放器显示层
@property (nonatomic, strong) ZJZDanMu *danmuLayer;                         // 弹幕
@property (nonatomic, strong) PLVLivePlayerController *livePlayer;          // PLV播放器
@property (nonatomic, assign) NSUInteger channelId;
@property (nonatomic, strong) NSString *userId;
@property (nonatomic, strong) NSString *stream;
@end

@implementation LivePlayerViewController {
    BOOL _allowLandscape;
}

#pragma mark - Lifecycle

- (void)dealloc {
    NSLog(@"-[%@ %@]",NSStringFromClass([self class]),NSStringFromSelector(_cmd));
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 判断是否有权限进入房间
        [self initLocalData];
        [self loadPlayer];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    _allowLandscape = YES;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Initialize

- (void)initLocalData {
    self.userId = self.channel.userId;
    self.stream = self.channel.stream;
    self.channelId = self.channel.channelId.unsignedIntegerValue;
}

- (void)loadPlayer {
    self.livePlayer = [self initializeLivePlayer];
    
    __weak typeof(self)weakSelf = self;
    [PLVLiveAPI getStreamStatusWithChannelId:self.channelId stream:self.stream completion:^(PLVLiveStreamState streamState, NSString *mode) {
        if (streamState == PLVLiveStreamStateNoStream) {
//            [weakSelf.livePlayer playWithCover];
        }else {
            [weakSelf.livePlayer play];
        }
    } failure:^(PLVLiveErrorCode errorCode, NSString *description) {
        [weakSelf.livePlayer play];
    }];
    
    // 注册播放器通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(livePlayerReconnectNotification:) name:PLVLivePlayerReconnectNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(livePlayerWillChangeToFullScreenNotification) name:PLVLivePlayerWillChangeToFullScreenNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(livePlayerWillExitFullScreenNotification) name:PLVLivePlayerWillExitFullScreenNotification object:nil];
}


#pragma mark - Live Player

- (UIView *)displayView {
    if (!_displayView) {
        CGFloat width = self.view.bounds.size.width;
        // 初始化一个播放器显示层，用于显示直播内容（默认为竖屏模式，横屏模式需要按需修改）
        CGFloat y = [PLVUtils statusBarHeight];
        CGRect rect = CGRectMake(0, 0, width, width * 9 / 16 + y);
        _displayView = [[UIView alloc] initWithFrame:rect];
        _displayView.backgroundColor = [UIColor blackColor];
        //_displayView.layer.contents = (id)[UIImage imageNamed:PLAYER_BACKGROUND].CGImage;  // 播放器背景图
        [self.view addSubview:_displayView];
    }
    return _displayView;
}

- (ZJZDanMu *)danmuLayer {
    if (!_danmuLayer) {
        _danmuLayer = [[ZJZDanMu alloc] initWithFrame:CGRectMake(0, 20, CGRectGetWidth(self.displayView.bounds), CGRectGetHeight(self.displayView.bounds) -20)];
    }
    return _danmuLayer;
}

- (PLVLivePlayerController *)initializeLivePlayer {
    if (_livePlayer) {
        [_livePlayer clearPlayer];
        _livePlayer = nil ;
    }
    _livePlayer = [[PLVLivePlayerController alloc] initWithChannel:self.channel displayView:self.displayView];
    //[IJKFFMoviePlayerController setLogLevel:k_IJK_LOG_INFO];    // 日志等级
    [self configCallBackBlock];
    
//    [_livePlayer insertDanmuView:self.danmuLayer]; // 添加弹幕层
  
    return _livePlayer;
}

- (void)configCallBackBlock {
    __weak typeof(self)weakSelf = self;
    [_livePlayer setReturnButtonClickBlock:^{
        NSLog(@"返回按钮点击了...");
        [weakSelf shutdownViewController];
    }];
    [_livePlayer setPlayButtonClickBlock:^{
        NSLog(@"播放按钮点击了...");
    }];
    [_livePlayer setPauseButtonClickBlock:^{
        NSLog(@"暂停按钮点击了...");
    }];
    [_livePlayer setFullScreenButtonClickBlock:^{
        NSLog(@"全屏按钮点击了...");
    }];
    [_livePlayer setSmallScreenButtonClickBlock:^{
        NSLog(@"小屏按钮点击了...");
    }];
    [_livePlayer setCoverImageBeClickedBlock:^(NSString *coverHref) {
        NSLog(@"点击了暖场图片，链接：%@",coverHref);
    }];
}

#pragma mark Notifications

// 直播播断流后重新连接时创建一个新的播放器
- (void)livePlayerReconnectNotification:(NSNotification *)notification {
    __weak typeof(self)weakSelf = self;
    [PLVLiveAPI loadChannelInfoRepeatedlyWithUserId:self.userId channelId:self.channelId completion:^(PLVLiveChannel *channel) {
        weakSelf.channel = channel;
        NSDictionary *userInfo = notification.userInfo;
        if (userInfo && userInfo[@"definition"]) {
            [weakSelf.channel updateDefaultDefinitionWithDefinition:userInfo[@"definition"]];
        }
        weakSelf.livePlayer = [weakSelf initializeLivePlayer];
        [weakSelf.livePlayer play];
    } failure:^(PLVLiveErrorCode errorCode, NSString *description) {
        NSLog(@"errorCode:%ld, description:%@",errorCode,description);
    }];
}

- (void)livePlayerWillChangeToFullScreenNotification {
    NSLog(@"将要全屏啦");
    [self.view endEditing:YES];
}

- (void)livePlayerWillExitFullScreenNotification {
    NSLog(@"将要退出全屏啦");
}

#pragma mark - Public

- (void)shutdownViewController {
    [self.livePlayer clearPlayer];
    [self dismissViewControllerAnimated:YES completion:nil];
    //[self.navigationController popViewControllerAnimated:YES]; // todo else
}

#pragma mark - Private methods

- (void)showNoPermissionAlert {
    __weak typeof(self)weakSelf = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"您未被授权观看本直播" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf shutdownViewController];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}


#pragma mark - View controller

- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (_allowLandscape) {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    }else {
        return UIInterfaceOrientationMaskPortrait;
    }
}

@end
